<%@ page import="org.bson.Document" %>
<%@ page import="com.mongodb.client.*" %>
<%@ page import="org.bson.conversions.Bson" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.LinkedList" %>
<%@ page import="com.google.gson.Gson" %>
<%@ page import="java.io.PrintWriter" %>
<%@ page import="java.util.ArrayList" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
    String url = "mongodb://g08:abc%408@mongo.zhledu.cn:27017/g08";
    MongoClient client = MongoClients.create(url);
    MongoIterable<String> names = client.listDatabaseNames();
    MongoDatabase g08 = client.getDatabase("g08");
    MongoCollection<Document> collection = g08.getCollection("student");

    List<Bson> queryList2 = new LinkedList<>();
    Document group2 = new Document();
    group2.append("$group", new Document("_id", "$sex").append("count", new Document("$sum", 1)));
    queryList2.add(group2);
    final AggregateIterable<Document> sexList = collection.aggregate(queryList2);
    List<Document> list=new ArrayList<>();
    for(Document doc : sexList){
        list.add(new Document("name",doc.getString("_id")).append("value",doc.getInteger("count")));
    }
    response.setCharacterEncoding("utf-8");
    response.setContentType("application/json");
    Gson gson = new Gson();
    PrintWriter writer = response.getWriter();
    writer.write(gson.toJson(list));
    writer.flush();
%>
